package com.lidx.back.statistics.controller.admin;

import java.io.IOException;
import java.net.URLDecoder;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("weather")
public class WeatherController {

	@RequestMapping(value="query",method=RequestMethod.GET,produces={"application/json;charset=UTF-8"})
	public String getWeatherData(){
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String response = "";
		try {
            //用get方法发送http请求
            HttpGet get = new HttpGet("http://api.avatardata.cn/Weather/Query?key=86936fb3516b4fa6b7dce2a32f5f3a69&cityname=苏州");
            get.setHeader("Content-Type", "application/json; charset=utf-8");
            System.out.println("执行get请求:...."+get.getURI());
            CloseableHttpResponse httpResponse = null;
            //发送get请求
            httpResponse = httpClient.execute(get);
            try{
                //response实体
                HttpEntity entity = httpResponse.getEntity();
                if (null != entity){
                    System.out.println("响应状态码:"+ httpResponse.getStatusLine());
                    System.out.println("-------------------------------------------------");
                    response = EntityUtils.toString(entity,"utf-8");
                    response = URLDecoder.decode(response, "utf-8");
                }
            }
            finally{
                httpResponse.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            try{
                //closeHttpClient(httpClient);
            	 if (httpClient != null){
            		 httpClient.close();
                 }
            } catch (IOException e){
                e.printStackTrace();
            }
        }
	 return response;
	}
}
